from django.utils.translation import check_for_language, get_language_from_request
from django.conf import settings

import re

path_lang = re.compile(r'^/([a-z]{2}(?:-[a-z]{2})?)(?:/|$)')
SUPPORTED_LANGUAGES = dict(settings.LANGUAGES)

def get_language_from_request_l(request):
    """Additionally to the value returned by get_language_from_request
    returns a 'level', which is one of three values:
    - 2 if no language was provided in the url
    - 1 if the language is not recognized or not supported
    - 0 if the returned language was provided in the url
    """
    level = 2
    lang_code = path_lang.search(request.path)
    
    if lang_code:
        level = 1
        lang_code = lang_code.group(1)

        if lang_code and lang_code not in SUPPORTED_LANGUAGES:
            lang_code = lang_code.split('-')[0] # e.g. if fr-ca is not supported fallback to fr
        if lang_code and lang_code in SUPPORTED_LANGUAGES and check_for_language(lang_code):
            return lang_code, 0
    
    return get_language_from_request(request), level


def set_language_into_url(path, lang_code, level):
    if level is 2:
        return '/%s%s' % (lang_code, path)
    elif level is 1:
        values = path.split('/', 2)
        if len(values) > 1:
            values[1] = lang_code
        return '/'.join(values)
    else:
        raise ValueError("Unsupported value for level.")